import { doLogin, getInfo,logOut } from '@/api/common'
import { getToken, setToken, removeToken } from '@/utils/auth'


const user = {
  state: {
    userId: '',
    userNo:  '',
    loginStatus: false,
  },
  //同步方法
  mutations: {
    // SET_TOKEN: (state, token) => {
    //   state.token = token
    // },
    SET_USER_ID: (state, value) => {
      // setToken('userId',userId)
      state.userId = value
    },
    SET_USER_NO: (state, value) => {
      //setToken('name',name)
      state.userNo = value
    },
    SET_LOGIN_STATUS: (state, value) => {
      //setToken('name',name)
      state.loginStatus = value
    },
  },
  //异步方法
  actions: {
    // 登录
    Login({ commit }, userNo,pwd) {
      return new Promise((resolve, reject) => {
        doLogin(userNo.trim(),pwd.trim()).then(res => {
          setToken(res.data.tokenValue)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    loginToten({ commit }, token) {
       setToken(token)
    },
    // 获取用户信息
    GetInfo({ commit }) {
      if(getToken()){
          getInfo().then(res => {
            commit('SET_USER_ID', res.data.id)
            commit('SET_USER_NO', res.data.userNo)
            commit('SET_LOGIN_STATUS', true)
          return res;
          }).catch(error => {
          })
      }
    },
    // 退出系统
    LogOut({ commit }) {
      return new Promise(resolve => {
        logOut().then(res => {
          commit('SET_USER_ID', '')
          commit('SET_USER_NO', '')
          commit('SET_LOGIN_STATUS', false)
          removeToken()
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user
